const express = require('express');
const router = express.Router();
const EmissionFactor = require('../models/emissionFactor');

// 碳排放计算器路由
router.post('/calculate', async (req, res) => {
  try {
    const { activityType, duration, distance, quantity } = req.body;
    
    // 从数据库获取排放因子
    const factor = await EmissionFactor.findOne({ activityType });
    if (!factor) return res.status(400).json({ error: '无效的活动类型' });

    // 计算碳排放量
    let emission = 0;
    switch(factor.unitType) {
      case 'time':
        emission = duration * factor.co2ePerUnit;
        break;
      case 'distance':
        emission = distance * factor.co2ePerUnit;
        break;
      case 'quantity':
        emission = quantity * factor.co2ePerUnit;
        break;
    }

    res.json({ 
      emission: emission.toFixed(2),
      suggestions: factor.reductionTips
    });

  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router;